package io.renren.modules.app.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.modules.app.dao.ResidentDao;
import io.renren.modules.app.entity.ResidentEntity;
import io.renren.modules.app.entity.UserEntity;
import io.renren.modules.app.service.ResidentService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.exception.RRException;

@Service("ResidentService")
public class ResidentServiceImpl extends ServiceImpl<ResidentDao, ResidentEntity> implements ResidentService {


    public ResidentEntity queryByIphoneAndId(String iPhone, String ID) {
        return baseMapper.selectOne(new QueryWrapper<ResidentEntity>().eq("iphone", iPhone).eq("ID", ID));
    }
    @Override
    public ResidentEntity queryByOpenid(String openId) {
        return baseMapper.selectOne(new QueryWrapper<ResidentEntity>().eq("open_id", openId));
    }

    @Override
    public void updateOpenIdByIphoneAndId(String openId, String iPhone, String ID) {
        ResidentEntity user = baseMapper.selectOne(new QueryWrapper<ResidentEntity>().eq("iphone", iPhone).eq("ID", ID));
        if (user != null) {
            user.setOpenId(openId);
            baseMapper.updateById(user);
        } else {
            throw new RRException("User not found");
        }
    }

    public ResidentEntity updateResidentInfo(ResidentEntity newResident) {
        // 使用user_id查找要更新的用户
        ResidentEntity oldResident = baseMapper.selectById(newResident.getUserId());
        if (oldResident != null) {
            // 将新的信息设置到找到的用户上
            oldResident.setIphone(newResident.getIphone());
            oldResident.setPicture(newResident.getPicture());
            oldResident.setName(newResident.getName());
            oldResident.setSex(newResident.getSex());
            oldResident.setCardealer(newResident.getCardealer());
            // 使用mybatis/mybatis-plus的更新函数进行更新
            baseMapper.updateById(oldResident);
        } else {
            throw new RRException("User not found");
        }
        return oldResident;
    }

    public ResidentEntity getUserById(int userId) {

        return baseMapper.selectById(userId);
    }

}
